<?php

namespace App\Http\Controllers\Api\Admin;

use App\ActivityGroupPrice;
use App\Comment;
use App\CommentImg;
use App\DiscountSalesRule;
use App\DiscountXGoods;
use App\Goods;
use App\GoodsBanner;
use App\GoodsImg;
use App\GoodSpu;
use App\GoodsSpu;
use App\Http\Services\FileManager;
use App\ShowGoods;
use Illuminate\Http\Request;
use Hash;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{
    public function setGoods(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录！']);

        $ssn                       = $request->get('ssn');
        $name                      = $request->get('name');
        $mPrice                    = $request->get('m_price');
        $sPrice                    = $request->get('s_price');
        $imgId                     = $request->get('thumb_id');
        $info                      = $request->get('info');
        $isShop                    = $request->get('is_shop');
        $isRecommend               = $request->get('is_recommend');
        $isSelling                 = $request->get('is_selling');
        $isNew                     = $request->get('is_new');
        $sort                      = $request->get('sort');
        $classifyId                = $request->get('classify_id');
        $classifyTwoId             = $request->get('classify_two_id');
//        $shopTime                  = $request->get("shop_time");
//        $integral                  = $request->get('integral');
        $id                        = !is_null($request->get('id'))?$request->get('id'):0;
        $isFreeShipping            = $request->get('isFreeShipping');
        $exchangeIntegral          = $request->get('exchangeIntegral');
        $type                      = $request->get('type');
        $weight                    = $request->get('weight');
        $detail                    = $request->get('detail');
        $discount_sales_rule_ids   = $request->get('discount_sales_rule_ids');

        $newGoods = Goods::whereId($id)->first();



        if(!$newGoods)
            $newGoods = new Goods();

        if(!is_null($ssn))$newGoods->ssn                        = trim($ssn);
        if(!is_null($name))$newGoods->name                      = trim($name);
        if(!is_null($mPrice))$newGoods->m_price                 = $mPrice;
        if(!is_null($sPrice))$newGoods->s_price                 = $sPrice;
        if(!is_null($imgId))$newGoods->thumb_id                 = $imgId;
        if(!is_null($info))$newGoods->info                      = $info;
        if(!is_null($isShop))$newGoods->is_shop                 = $isShop;
        if(!is_null($isRecommend))$newGoods->is_recommend       = $isRecommend;
        if(!is_null($isSelling))$newGoods->is_selling           = $isSelling;
        if(!is_null($isNew))$newGoods->is_new                   = $isNew;
        if(!is_null($sort))$newGoods->sort                      = $sort;
        if(!is_null($classifyId))$newGoods->classify_id         = $classifyId;
        if(!is_null($classifyTwoId))$newGoods->classify_two_id  = $classifyTwoId;
//        if(!is_null($integral))$newGoods->integral              = $integral;
//        if(!is_null($shopTime))$newGoods->shop_time             = $shopTime;
        if(!is_null($isFreeShipping))$newGoods->is_free_shipping= $isFreeShipping;
        if(!is_null($exchangeIntegral))$newGoods->exchange_integral=$exchangeIntegral;
        if(!is_null($type))                    $newGoods->type=$type;
        if(!is_null($weight))                  $newGoods->weight=$weight;
        if(!is_null($detail))                  $newGoods->detail=$detail;
        $newGoods->save();


        $newGoodsSpu=GoodsSpu::whereGoodsId($newGoods->id)->get();

        if(count($newGoodsSpu)<1){
            $newGoodsSpu = new GoodsSpu();
            $newGoodsSpu->goods_id      = $newGoods->id;
            $newGoodsSpu->size_spu_name       = '标准';
            $newGoodsSpu->color_spu_name      = '标准';
            $newGoodsSpu->specification_code  = '默认';
            $newGoodsSpu->price         = $newGoods->s_price;
            $newGoodsSpu->status        = 1;
            $newGoodsSpu->save();
        }


        $newGoods->link_url="/pages/goodsDetail/main?id=".$newGoods->id;
        $newGoods->save();

        $exist_rules_ids    =DiscountXGoods::whereGoodsId($newGoods->id)->pluck('discount_sales_rule_id')->toArray();
        $add_rules_ids      =array_diff($discount_sales_rule_ids,$exist_rules_ids);
        $delete_rules_ids   =array_diff($exist_rules_ids,$discount_sales_rule_ids);
        if (count($add_rules_ids) > 0){
            foreach ($add_rules_ids as $add_rules_id){
                $rule=DiscountSalesRule::whereId($add_rules_id)->first();
                if ($rule){
                    $exist=DiscountXGoods::whereGoodsId($newGoods->id)->whereDiscountSalesRuleId($add_rules_id)->first();
                    if (!$exist){
                        $newGoodsRule=new DiscountXGoods();
                        $newGoodsRule->discount_sales_rule_id=$add_rules_id;
                        $newGoodsRule->goods_id=$newGoods->id;
                        $newGoodsRule->save();
                    }
                }
            }
        }

        if (count($delete_rules_ids) > 0){
            DiscountXGoods::whereGoodsId($newGoods->id)->whereIn('discount_sales_rule_id',$delete_rules_ids)->delete();
        }



//        $thisShowGoods = ShowGoods::whereId(1)->first();
//        if(!$thisShowGoods)
//            $thisShowGoods = new ShowGoods();
//
//        if(!is_null($showGoodsOne))$thisShowGoods->show_goods_one = $showGoodsOne;
//        $thisShowGoods->save();

        return response()->json(['level' => 'success','message' => '添加或修改成功',"data"=>$newGoods]);
    }

    public function delGoods(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;
        $thatGoods =Goods::whereId($id)->first();

        if(!$thatGoods)
            return response()->json(["level"=>"error","message"=>"该商品不存在！"]);

        $thatGoods->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatGoods]);
    }
    
    public function setGoodsImg(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $thumbId = !is_null($request->get('thumb_id')) ? $request->get('thumb_id') : 0;
        $id      = !is_null($request->get('id'))?$request->get('id'):0;


        $isGoods = Goods::whereId($goodsId)->first();
        if(!$isGoods)
            return response()->json(['level' => 'error','message' => '商品不存在']);

        $newGoodsImg = GoodsImg::whereId(trim($id))->first();
        if(!$newGoodsImg)
            $newGoodsImg = new GoodsImg();

        $newGoodsImg->good_id  = $goodsId;
        $newGoodsImg->thumb_id = $thumbId;
        $newGoodsImg->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newGoodsImg]);
    }

    public function delGoodsImg(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatGoodsImg =GoodsImg::whereId($id)->first();

        if(!$thatGoodsImg)
            return response()->json(["level"=>"error","message"=>"该商品不存在！"]);

        $thatGoodsImg->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatGoodsImg]);
    }

    public function setGoodsBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $imgId   = !is_null($request->get('img_id')) ? $request->get('img_id') : 0;
        $sort    = !is_null($request->get('sort')) ? $request->get('sort') : 0;
        $id      = !is_null($request->get('id'))?$request->get('id'):0;


        $isGoods = Goods::whereId($goodsId)->first();
        if(!$isGoods)
            return response()->json(['level' => 'error','message' => '商品不存在']);

        $newGoodsBanner = GoodsBanner::whereId(trim($id))->first();
        if(!$newGoodsBanner)
            $newGoodsBanner = new GoodsBanner();

        $newGoodsBanner->goods_id  = $goodsId;
        $newGoodsBanner->img_id   = $imgId;
        $newGoodsBanner->sort    = $sort;
        $newGoodsBanner->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newGoodsBanner]);
    }

    public function delGoodsBanner(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        $thatGoodsBanner =GoodsBanner::whereId($id)->first();

        if(!$thatGoodsBanner)
            return response()->json(["level"=>"error","message"=>"该商品不存在！"]);

        $thatGoodsBanner->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatGoodsBanner]);
    }

    public function delGoodsComment(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id =!is_null($request->get('id')) ? $request->get('id') : 0;

        $thisGoodsComment = Comment::whereId($id)->first();
        if(!$thisGoodsComment)
            return response()->json(['level' => 'error','message' => '该评论不存在']);

        $thisGoodsComment->delete();

        return response()->json(['level' => 'success','message' => '删除成功!','data' => $thisGoodsComment]);
    }

    public function setGoodsComment(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id =!is_null($request->get('id')) ? $request->get('id') : 0;

        $thisGoodsComment = Comment::whereId($id)->first();
        if(!$thisGoodsComment)
            return response()->json(['level' => 'error','message' => '该评论不存在']);

        $thisGoodsComment->is_show= $thisGoodsComment->is_show ? 0 :1;
        $thisGoodsComment->save();
        $message='已'.($thisGoodsComment->is_show ? '公开展示' : '隐藏');

        return response()->json(['level' => 'success','message' => $message,'data' => $thisGoodsComment]);
    }

    public function delGoodsCommentImg(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisGoodsCommentImg = CommentImg::whereId($id)->first();
        if(!$thisGoodsCommentImg)
            return response()->json(['level' => 'error','message' => '该图片不存在']);

        $thisGoodsCommentImg->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisGoodsCommentImg]);
    }

    public function setGoodsSpu(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        $spuName = $request->get('spu_name');
        $price = $request->get('price');
        $goodsId = $request->get("goods_id");
        $stock = $request->get('stock');
        $sort = $request->get('sort');
        $status = $request->get('status');
        $type = !is_null($request->get('type')) ? $request->get('type') : '';
        $size_spu_name  = !is_null($request->get('size_spu_name')) ? $request->get('size_spu_name') : '';
        $color_spu_name = !is_null($request->get('color_spu_name')) ? $request->get('color_spu_name') : '';
        $specification_code = !is_null($request->get('specification_code')) ? $request->get('specification_code') : '';
        $img_id = !is_null($request->get('img_id')) ? $request->get('img_id') : 0;
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        $thisGoods=Goods::whereId($goodsId)->first();
        if (!$thisGoods)
            return response()->json(['level'=>'error','message'=>'商品不存在']);

        $newGoodsSpu = GoodsSpu::whereId($id)->whereGoodsId($goodsId)->first();
        if(!$newGoodsSpu)
            $newGoodsSpu = new GoodsSpu();

        if(!is_null($spuName))$newGoodsSpu->spu_name            = trim($spuName);
        if(!is_null($price))$newGoodsSpu->price                 = $price;
        if(!is_null($goodsId))$newGoodsSpu->goods_id            = $goodsId;
        if(!is_null($stock))$newGoodsSpu->stock                 = trim($stock);
        if(!is_null($sort))$newGoodsSpu->sort                   = $sort;
        if(!is_null($status))$newGoodsSpu->status               = $status;

        if($size_spu_name) $newGoodsSpu->size_spu_name          = trim($size_spu_name);
        if(!is_null($color_spu_name))$newGoodsSpu->color_spu_name       = trim($color_spu_name);
        if(!is_null($specification_code))$newGoodsSpu->specification_code             = trim($specification_code);
        if($img_id) $newGoodsSpu->img_id             = $img_id;
//        if ($type)           $newGoodsSpu->type               = $type;
        $newGoodsSpu->save();
        $newGoodsSpu->thumb_url=FileManager::getImgUrl($newGoodsSpu->img_id);

//        if($type == 'group'){
//            $newActivityGroupPrice = ActivityGroupPrice::whereGoodsSpuId($newGoodsSpu->id)->whereGoodsId($newGoodsSpu->goods_id)->whereActivityGroupId($activityGroupId)->first();
//            if(!$newActivityGroupPrice)
//                $newActivityGroupPrice = new ActivityGroupPrice();
//
//            $newActivityGroupPrice->activity_group_id      = $activityGroupId;
//            $newActivityGroupPrice->goods_id               = $goodsId;
//            $newActivityGroupPrice->goods_spu_id           = $newGoodsSpu->id;
//            $newActivityGroupPrice->many_price             = $manyPrice;
//            $newActivityGroupPrice->save();
//        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newGoodsSpu]);
    }

    public function addGoodsSpuArray(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);
        $spu_arr = $request->get('spu_arr');
        $goods_id= $request->get('goods_id');
        if (!$goods_id)
            return response()->json(['level'=>'error','message'=>'商品id错误']);
        $result=[];
        $thisGoods=Goods::whereId($goods_id)->first();
        if (!$thisGoods)
            return response()->json(['level'=>'error','message'=>'商品不存在']);
        if (count($spu_arr) > 0){
            foreach ($spu_arr as $spu){
                $newSpu                 =new GoodsSpu();
                $newSpu->goods_id       =$goods_id      ? $goods_id : 0;
                $newSpu->img_id         =isset($spu[0])&&$spu[0]!='' ? $spu[0] : $thisGoods->thumb_id;
                $newSpu->size_spu_name  =isset($spu[1])&&$spu[1]!='' ? trim($spu[1]) : '普通';
                $newSpu->color_spu_name =isset($spu[2])&&$spu[2]!='' ? trim($spu[2]) : '普通';
                $newSpu->specification_code = isset($spu[3])&&$spu[3]!='' ? trim($spu[3]) : '';
                $newSpu->price          =isset($spu[4])&&$spu[4]!='' ? $spu[4] : 0;
                $newSpu->stock          =isset($spu[5])&&$spu[5]!='' ? $spu[5] : 0;
                $newSpu->sort           =isset($spu[6])&&$spu[6]!='' ? $spu[6] : 0;
                $newSpu->status         =isset($spu[7])&&$spu[7]!='' ? $spu[7] : 0;
                $newSpu->save();
                $newSpu->thumb_url        =FileManager::getImgUrl($newSpu->img_id);
                array_push($result,$newSpu);
            }
        }
        return response()->json(['level'=>'success','message'=>'批量保存成功','data'=>$result]);
    }

    public function delGoodsSpu(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var GoodsSpu $thisGoodsSpu */
        $thisGoodsSpu = GoodsSpu::whereId($id)->first();
        if(!$thisGoodsSpu)
            return response()->json(['level' => 'error','message' => '该图片不存在']);

        /** @var ActivityGroupPrice $thisGroupPrice */
        $thisGroupPrice = ActivityGroupPrice::whereGoodsSpuId($thisGoodsSpu->id)->first();
        if($thisGroupPrice){
            $thisGroupPrice->delete();
        }

        $thisGoodsSpu->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisGoodsSpu]);
    }

    public function setComment(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        $goodsId   = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $nickname  = !is_null($request->get('nickname')) ? $request->get('nickname') : '';
        $photoId   = !is_null($request->get('photo_id')) ? $request->get('photo_id') : 0;
        $content   = !is_null($request->get('content')) ? $request->get('content') : '';

        if($nickname == '')
            return response()->json(['level' => 'error','message' => '请输入昵称']);

        if($photoId == 0 || $photoId == '')
            return response()->json(['level' => 'error','message' => '请传入头像']);

        if($content == '')
            return response()->json(['level' => 'error','message' => '请输入评论内容']);

        $newComment = new Comment();
        $newComment->goods_id        = $goodsId;
        $newComment->nickname        = $nickname;
        $newComment->photo_id        = $photoId;
        $newComment->content         = $content;
        $newComment->is_show         = 1;
        $newComment->save();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $newComment]);
    }

    public function setCommentImg(Request $request){
        if(Auth::guard('admin')->guest())
            return response()->json(['level' => 'error','message' => '请先登录!']);

        $imgId     = !is_null($request->get('img_id')) ? $request->get('img_id') : 0;
        $commentId = !is_null($request->get('comment_id')) ? $request->get('comment_id') : 0;

        if($imgId == 0 || $imgId == '')
            return response()->json(['level' => 'error','message' => '请传入图片']);

        $newCommentImg = new CommentImg();
        $newCommentImg->comment_id        = $commentId;
        $newCommentImg->img_id            = $imgId;
        $newCommentImg->save();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $newCommentImg]);
    }
    public function trim(){
        $spu=GoodsSpu::all();
        if (count($spu)> 0){
            /** @var GoodsSpu $item */
            foreach ($spu as $item){
                $item->size_spu_name=trim($item->size_spu_name);
                $item->color_spu_name=trim($item->color_spu_name);
                $item->specification_code=trim($item->specification_code);
                $item->save();
            }
        }
        return response()->json(['level'=>'success','message'=>'trim success']);

    }
}
